package com.kele.readAndWrite;



import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author kele
 * @date 2021/10/11 15:52
 * @description
 */
public class ReadWriteTest {
    public static void main(String[] args) {
        MyCache cache=new MyCache();
        for (int i = 1; i <=5 ; i++) {
            final int temp=i;
            new Thread(()->{
                cache.put(temp+"",temp+"");
            },String.valueOf(i)).start();
        }
        for (int i = 1; i <=5 ; i++) {
            final int temp=i;
            new Thread(()->{
                cache.get(temp+"");
            },String.valueOf(i)).start();
        }
    }
}

class MyCache{
    private volatile Map<String, Object> map=new HashMap<>();
    private  ReadWriteLock readWriteLock=new ReentrantReadWriteLock();

    /**
     * 写操作要保证同步
     * @param key
     * @param value
     */
    public void put(String key,Object value){
        readWriteLock.writeLock().lock();
        try {
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"写入"+key);
            System.out.println(Thread.currentThread().getName()+"写入完毕");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.writeLock().unlock();
        }

    }

    public void get(String key){
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"读取"+key);
            Object o = map.get(key);
            System.out.println(Thread.currentThread().getName()+"读取成功 : "+o);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.readLock().unlock();
        }
    }
}
